package com.mentalhealth.diary.service.impl;

import com.mentalhealth.diary.entity.Member;
import com.mentalhealth.diary.mapper.MemberMapper;
import com.mentalhealth.diary.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

/**
 * 会员服务实现类
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Member openExperienceMember(Long userId) {
        // 检查是否已开通会员
        Member existingMember = memberMapper.selectByUserId(userId);
        if (existingMember != null) {
            // 如果已有会员且未过期，直接返回
            if (existingMember.getExpireTime() != null && existingMember.getExpireTime().after(new Date())) {
                return existingMember;
            }
            // 更新会员信息
            existingMember.setMemberType(1); // 体验会员
            existingMember.setExpireTime(getExperienceExpireTime());
            existingMember.setUpdateTime(new Date());
            memberMapper.updateById(existingMember);
            return existingMember;
        }
        // 创建新的会员记录
        return createMember(userId, 1, getExperienceExpireTime());
    }

    @Override
    public Member getUserMember(Long userId) {
        return memberMapper.selectByUserId(userId);
    }

    @Override
    public boolean updateMember(Member member) {
        member.setUpdateTime(new Date());
        return memberMapper.updateById(member) > 0;
    }

    @Override
    public Member createMember(Long userId, Integer memberType, Date expireTime) {
        Member member = new Member();
        member.setUserId(userId);
        member.setMemberType(memberType);
        member.setExpireTime(expireTime);
        member.setCreateTime(new Date());
        member.setUpdateTime(new Date());
        member.setStatus(1); // 有效状态
        memberMapper.insert(member);
        return member;
    }

    /**
     * 计算体验会员过期时间（当前时间+3天）
     */
    private Date getExperienceExpireTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 3);
        return calendar.getTime();
    }
}